package com.wu.dms.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.wu.dms.cache.UrlCache;
import com.wu.constant.Enum.MinIoNameEnum;
import com.wu.dms.dao.entity.Banner;
import com.wu.dms.dao.entity.SongList;
import com.wu.dms.dao.entity.Singer;
import com.wu.dms.dao.entity.Song;
import com.wu.dms.service.*;

import com.wu.dms.util.MinIoUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * @author Cousin
 * @date 2024/12/17
 * @Description
 */
@Service
@Slf4j
public class CacheServiceImpl implements CacheService {
    @Resource
    MinIoUtil minIoUtil;
    @Resource
    SongService songService;
    @Resource
    SingerService actorService;
    @Resource
    SongListService songListService;
    @Resource
    BannerService bannerService;


    // 定义一个固定大小的线程池
    ExecutorService workService = Executors.newFixedThreadPool(10);
    @Override
    public void refreshAccessibleUrls() {
        // 创建一个线程池来处理并行任务
        ExecutorService executorService = Executors.newFixedThreadPool(4);

        Map<String, Map<String, String>> urlCacheMap = new ConcurrentHashMap<>();

        try {
            // 提交任务并获取返回的Future对象
            Future<Map<String, String>> songUrlFuture = executorService.submit(this::getSongUrls);
            Future<Map<String, String>> songImageUrlFuture = executorService.submit(this::getSongImageUrls);
            Future<Map<String, String>> actorImageUrlFuture = executorService.submit(this::getSingerImageUrls);
            Future<Map<String, String>> playListImageUrlFuture = executorService.submit(this::getPlayListImageUrls);
            Future<Map<String, String>> bannerImageUrlFuture = executorService.submit(this::getBannerImageUrls);

            // 等待所有任务执行完毕并获取结果
            Map<String, String> songUrlMap = songUrlFuture.get();
            Map<String, String> songImageUrlMap = songImageUrlFuture.get();
            Map<String, String> actorImageUrlMap = actorImageUrlFuture.get();
            Map<String, String> playListImageUrlMap = playListImageUrlFuture.get();

            // 将结果存储到 urlCacheMap
            if (CollectionUtils.isNotEmpty(songUrlMap)) {
                urlCacheMap.put(MinIoNameEnum.SONG.getBucketName(), songUrlMap);
            }
            if (CollectionUtils.isNotEmpty(songImageUrlMap)) {
                urlCacheMap.put(MinIoNameEnum.SONG_IMAGE.getBucketName(), songImageUrlMap);
            }
            if (CollectionUtils.isNotEmpty(actorImageUrlMap)) {
                urlCacheMap.put(MinIoNameEnum.SINGER_IMAGE.getBucketName(), actorImageUrlMap);
            }
            if (CollectionUtils.isNotEmpty(playListImageUrlMap)) {
                urlCacheMap.put(MinIoNameEnum.SONG_LIST_IMAGE.getBucketName(), playListImageUrlMap);
            }
            UrlCache.set(urlCacheMap);
        } catch (InterruptedException | ExecutionException e) {
           log.error("URL缓存出现问题：{}",e.toString());
        } finally {
            executorService.shutdown();  // 确保线程池关闭
        }
    }

    /**
     * 获取歌曲URL缓存
     */
    private Map<String, String> getSongUrls() {
        List<Song> songList = songService.query().list();
        Map<String, String> songUrlMap = new ConcurrentHashMap<>();

        if (CollectionUtil.isNotEmpty(songList)) {
            // 等待所有任务完成
            CompletableFuture.allOf(songList.stream()
                    .map(song -> CompletableFuture.runAsync(() -> {
                        String objectName = MinIoNameEnum.getDefaultObjectName(song.getId(), song.getUrl());
                        if(!minIoUtil.doesFileExist(MinIoNameEnum.SONG.getBucketName(),objectName)){
                            return;
                        }
                        String songUrl = minIoUtil.getFileUrlDefault(MinIoNameEnum.SONG.getBucketName(), objectName);
                        if (songUrl != null && !songUrl.isEmpty()) {
                            songUrlMap.put(objectName, songUrl);
                        }
                    }, workService)).toArray(CompletableFuture[]::new)).join();
        }
        return songUrlMap;
    }

    /**
     * 获取歌曲照片URL
     */
    public Map<String, String> getSongImageUrls(){
        List<Song> songList = songService.query().list();
        Map<String, String> songImageUrlMap = new ConcurrentHashMap<>();

        if (songList != null && !songList.isEmpty()) {
            // 等待所有任务完成
            CompletableFuture.allOf(songList.stream()
                    .map(song -> CompletableFuture.runAsync(() -> {

                        if (MinIoNameEnum.SONG_IMAGE.getDefaultObjectName().equals(song.getPic())){
                            return;
                        }
                        String objectName = MinIoNameEnum.getDefaultObjectName(song.getId(), song.getPic());
                        if(!minIoUtil.doesFileExist(MinIoNameEnum.SONG_IMAGE.getBucketName(),objectName)){
                            return;
                        }
                        String songImageUrl = minIoUtil.getFileUrlDefault(MinIoNameEnum.SONG_IMAGE.getBucketName(), objectName);
                        if (songImageUrl != null && !songImageUrl.isEmpty()) {
                            songImageUrlMap.put(objectName, songImageUrl);
                        }
                    }, workService)).toArray(CompletableFuture[]::new)).join();

        }
        String defaultSongImageUrl = minIoUtil.getFileUrlDefault(MinIoNameEnum.SONG_IMAGE.getBucketName(), MinIoNameEnum.SONG_IMAGE.getDefaultObjectName());
        if (defaultSongImageUrl!= null && !defaultSongImageUrl.isEmpty()) {
            songImageUrlMap.put(MinIoNameEnum.SONG_IMAGE.getBucketName(), defaultSongImageUrl);
        }
        return songImageUrlMap;
    }
    /**
     * 获取歌手照片URL
     */
    private Map<String, String> getSingerImageUrls() {
        List<Singer> singerList = actorService.query().list();
        Map<String, String> actorImageUrlMap = new ConcurrentHashMap<>();
        if (CollectionUtil.isNotEmpty(singerList)) {
            // 等待所有任务完成
            CompletableFuture.allOf(singerList.stream()
                    .map(singer -> CompletableFuture.runAsync(() -> {
                        if (MinIoNameEnum.SINGER_IMAGE.getDefaultObjectName().equals(singer.getPic())){
                            return;
                        }
                        String objectName = MinIoNameEnum.getDefaultObjectName(singer.getId(), singer.getPic());
                        if(!minIoUtil.doesFileExist(MinIoNameEnum.SINGER_IMAGE.getBucketName(), objectName)){
                            return;
                        }
                        String songImageUrl = minIoUtil.getFileUrlDefault(MinIoNameEnum.SONG_IMAGE.getBucketName(), objectName);
                        if (songImageUrl != null && !songImageUrl.isEmpty()) {
                            actorImageUrlMap.put(objectName, songImageUrl);
                        }
                    }, workService)).toArray(CompletableFuture[]::new)).join();
        }
        String defaultSingerImageUrl = minIoUtil.getFileUrlDefault(MinIoNameEnum.SINGER_IMAGE.getBucketName(), MinIoNameEnum.SINGER_IMAGE.getDefaultObjectName());
        if (defaultSingerImageUrl!= null && !defaultSingerImageUrl.isEmpty()) {
            actorImageUrlMap.put(MinIoNameEnum.SINGER_IMAGE.getBucketName(), defaultSingerImageUrl);
        }
        return actorImageUrlMap;
    }
    /**
     * 获取歌单照片URL
     */
    private Map<String, String> getPlayListImageUrls() {
        List<SongList> songLists = songListService.query().list();
        Map<String, String> playListImageUrlMap = new ConcurrentHashMap<>();
        if (CollectionUtil.isNotEmpty(songLists)) {
            // 等待所有任务完成
            CompletableFuture.allOf(songLists.stream()
                    .map(playList -> CompletableFuture.runAsync(() -> {
                        if (MinIoNameEnum.SONG_LIST_IMAGE.getDefaultObjectName().equals(playList.getPic())){
                            return;
                        }
                        String objectName = MinIoNameEnum.getDefaultObjectName(playList.getId(), playList.getPic());
                        if(!minIoUtil.doesFileExist(MinIoNameEnum.SONG_LIST_IMAGE.getBucketName(), objectName)){
                            return;
                        }
                        String songImageUrl = minIoUtil.getFileUrlDefault(MinIoNameEnum.SONG_LIST_IMAGE.getBucketName(), objectName);
                        if (songImageUrl != null && !songImageUrl.isEmpty()) {
                            playListImageUrlMap.put(objectName, songImageUrl);
                        }
                    }, workService)).toArray(CompletableFuture[]::new)).join();
        }
        String defaultPlayListImageUrl = minIoUtil.getFileUrlDefault(MinIoNameEnum.SONG_LIST_IMAGE.getBucketName(), MinIoNameEnum.SONG_LIST_IMAGE.getDefaultObjectName());
        if (defaultPlayListImageUrl!= null && !defaultPlayListImageUrl.isEmpty()) {
            playListImageUrlMap.put(MinIoNameEnum.SONG_LIST_IMAGE.getBucketName(), defaultPlayListImageUrl);
        }
        return playListImageUrlMap;
    }
    /**
     * 获取歌单照片URL
     */
    private Map<String, String> getBannerImageUrls() {
        List<Banner> banners = bannerService.query().list();
        Map<String, String> bannerImageUrlMap = new ConcurrentHashMap<>();
        if (CollectionUtil.isNotEmpty(banners)) {
            // 等待所有任务完成
            CompletableFuture.allOf(banners.stream()
                    .map(banner -> CompletableFuture.runAsync(() -> {
                        String objectName = MinIoNameEnum.getDefaultObjectName(banner.getId(), banner.getPic());
                        if(!minIoUtil.doesFileExist(MinIoNameEnum.BANNER_IMAGE.getBucketName(), objectName)){
                            return;
                        }
                        String bannerImageUrl = minIoUtil.getFileUrlDefault(MinIoNameEnum.BANNER_IMAGE.getBucketName(), objectName);
                        if (bannerImageUrl != null && !bannerImageUrl.isEmpty()) {
                            bannerImageUrlMap.put(objectName, bannerImageUrl);
                        }
                    }, workService)).toArray(CompletableFuture[]::new)).join();
        }
        return bannerImageUrlMap;
    }


}
